//
//  ZCMeDataVC.m
//  zctx
//
//  Created by apple on 15/12/2.
//  Copyright © 2015年 sanliang. All rights reserved.
//

#import "ZCMeDataVC.h"
#import "JZMTBtnView.h"

#import "ZCUserNameVC.h"
#import "ZCTelephoneVC.h"
#import "ZCSexVC.h"

#import "ZCMeVCOneCell.h"
#import "ZCMeDataCell.h"

#import "ZCAdressVC.h"
#import "ZCMeBirthdayVC.h"

#import "FSMediaPicker.h"

@interface ZCMeDataVC ()<UITableViewDataSource,UITableViewDelegate,FSMediaPickerDelegate>{
    JZMTBtnView *btnView;
    UILabel *namelable;
}
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSString *timeStr;
@property (nonatomic,strong)NSDictionary *dataDict;

@property (nonatomic,strong)UIImage *headIconImage;

@property (nonatomic,strong)UIButton * rightButton;
@end

@implementation ZCMeDataVC

-(void)dealloc{
     [[NSNotificationCenter defaultCenter]removeObserver:self name:@"userinfo" object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ZCMeDataVC"];
    [MTA trackPageViewBegin:@"ZCMeDataVC"];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ZCMeDataVC"];
    [MTA trackPageViewEnd:@"ZCMeDataVC"];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"我的资料";
    [self initnavegation];
    self.view.backgroundColor =[UIColor colorWithHexString:@"#ebeded"];
    self.dataDict = [NSDictionary dictionary];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadUserInfo:) name:@"userinfo" object:nil];
    
    
    [self initTableView]; //初始化UITableView
    //    [self initTableViewHeader]; //创建TableviewHeader
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCMeVCOneCell" bundle:nil] forCellReuseIdentifier:@"meone"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCMeDataCell" bundle:nil] forCellReuseIdentifier:@"datacell"];
}

-(void)reloadUserInfo:(NSNotification *)noft{
    [self.rightButton setTitle:@"确认" forState:UIControlStateNormal];
    NSString *userinfo = [[noft userInfo]objectForKey:@"user"];
    if ([userinfo isEqualToString:@"4"]) {
        [self requestUserInfo];
    }else{
        [self.tableView reloadData];
    }
}


#pragma mark 导航栏
-(void)initnavegation{
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    if (self.nomobile ==1) {
        self.navigationItem.title = @"完善我的资料";
        [self.navigationItem setHidesBackButton:YES];
        self.rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 25)];
        [self.rightButton setTitle:@"跳过" forState:UIControlStateNormal];
        [self.rightButton addTarget:self action:@selector(skipClick) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem * barButtonItem_rightNavBar = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
        self.navigationItem.rightBarButtonItem = barButtonItem_rightNavBar;
        
        [[[iToast makeText:@"请填写手机号码"]setGravity:iToastGravityCenter] show];
    }else{
        self.navigationItem.leftBarButtonItem = barButtonItem_leftNavBar;
    }
}
#pragma mark 跳过
-(void)skipClick{

    CATransition *animation = [CATransition animation];
    animation.duration = 0.5;
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    animation.type = @"pageUnCurl";
    animation.type = kCATransitionFade;
    //    animation.subtype = kCATransitionFromBottom;
    [self.view.window.layer addAnimation:animation forKey:nil];
    
    [self dismissViewControllerAnimated:NO completion:^{
    }];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"skip" object:self];

}
//返回
-(void)backButtonPressed{
    ProgressDismiss;
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)requestUserInfo{
    
    [NetworkManager requestGetMemberInfoWithMid:UserModel.mid password:UserModel.password device_token:theAppdelegate.deviceToken success:^(NSDictionary *dictResponse) {
        NSDictionary *dict = [dictResponse objectForKey:@"content"];
        self.dataDict = [dict copy];
        
        NSString *adress = nil;
        if ([[dict objectForKey:@"province"]isEqualToString:[dict objectForKey:@"city"]]) {
            adress = [NSString stringWithFormat:@"%@%@",[dict objectForKey:@"city"],[dict objectForKey:@"address"]];
        }else{
            adress = [NSString stringWithFormat:@"%@%@%@",[dict objectForKey:@"province"],[dict objectForKey:@"city"],[dict objectForKey:@"address"]];
        }
        [UserModel setAddress:adress];
        
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}

-(void)initTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.sectionFooterHeight = 0.0001;
    self.tableView.separatorColor = RGB(236, 237, 238);
     self.tableView.backgroundColor = [UIColor colorWithHexString:@"#fafcfb"];
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
}

#pragma mark UITableViewDataSource,UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (section==0) {
        return 1;
    }else{
        return 5;
    }
        
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        static NSString *cellIndentifier = @"meone";
        ZCMeVCOneCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil) {
            cell = [[ZCMeVCOneCell alloc]initWithStyle:
                    UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapGestureRecognizerClick:)];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.headView addGestureRecognizer:recognizer];
        if (UserModel.avatar || self.headIconImage) {
            if (UserModel.avatar) {
                [cell.imgView sd_setImageWithURL:[NSURL URLWithString:UserModel.avatar] placeholderImage:[UIImage imageNamed:@"projectdetail_icon"]];
            }
            if (self.headIconImage) {
                cell.imgView.image = self.headIconImage;
            }
        }
        cell.nameLable.text = @"点击更换头像";
        return cell;
    }else{
        static NSString *cellIndentifier = @"datacell";
        ZCMeDataCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil) {
            cell = [[ZCMeDataCell alloc]initWithStyle:
                    UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        cell.titleLable.textColor = [UIColor colorWithHexString:@"#404040"];
        if (indexPath.row==0) {
            cell.titleLable.text =@"昵称";
            cell.infoLable.text = UserModel.username;
            cell.infoLable.textColor = [UIColor colorWithHexString:@"#8a8a8a"];
        }else if(indexPath.row==1){
            cell.titleLable.text = @"手机号码";
            if (UserModel.mobile) {
                cell.infoLable.text = [NSString stringWithFormat:@"%@",UserModel.mobile];
                cell.infoLable.textColor = [UIColor colorWithHexString:@"#8a8a8a"];
            }else{
                cell.infoLable.text = @"修改/添加";
                cell.infoLable.textColor = MainColor;
            }
        }else if (indexPath.row==2){
            cell.titleLable.text = @"性别";
            if (UserModel.gender) {
                NSString *sex =[NSString stringWithFormat:@"%@",UserModel.gender];
                if ([sex isEqualToString:@"1"]) {
                    cell.infoLable.text =@"男";
                    cell.infoLable.textColor = [UIColor colorWithHexString:@"#8a8a8a"];
                }else if([sex isEqualToString:@"0"]){
                    cell.infoLable.text =@"女";
                    cell.infoLable.textColor = [UIColor colorWithHexString:@"#8a8a8a"];
                }else{
                    cell.infoLable.textColor = MainColor;
                    cell.infoLable.text = @"修改/添加";
                }
            }else{
                cell.infoLable.textColor = MainColor;
                cell.infoLable.text = @"修改/添加";
            }
        }else if(indexPath.row==3){
            cell.titleLable.text = @"生日";
            if (UserModel.birthday) {
                cell.infoLable.text = [NSString stringWithFormat:@"%@",UserModel.birthday];
                cell.infoLable.textColor = [UIColor colorWithHexString:@"#8a8a8a"];
            }else{
                cell.infoLable.textColor = MainColor;
                cell.infoLable.text = @"修改/添加";
            }
        }else{
            cell.titleLable.text = @"地址";
            if (UserModel.address) {
                cell.infoLable.text = [NSString stringWithFormat:@"%@",UserModel.address];
                cell.infoLable.textColor = [UIColor colorWithHexString:@"#8a8a8a"];
            }else{
                cell.infoLable.textColor = MainColor;
                cell.infoLable.text = @"修改/添加";
            }
        }
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0) {
        return 145;
    }else{
        return 44;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0.000001;
    }else{
        return 4;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
  
    }else{
        if (indexPath.row==0) {
            ZCUserNameVC * namevc = [[ZCUserNameVC alloc]init];
            namevc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:namevc animated:YES];
        }else if (indexPath.row==1){
            ZCTelephoneVC * telehonevc = [[ZCTelephoneVC alloc]init];
            telehonevc.hidesBottomBarWhenPushed = YES;
            telehonevc.telephone =[NSString stringWithFormat:@"%@",[self.dataDict objectForKey:@"mobile"]];
            [self.navigationController pushViewController:telehonevc animated:YES];
        }else if (indexPath.row==2){
            ZCSexVC *sexvc = [[ZCSexVC alloc]init];
            sexvc.hidesBottomBarWhenPushed = YES;
            sexvc.sex = [NSString stringWithFormat:@"%@",[self.dataDict objectForKey:@"gender"]];
            [self.navigationController pushViewController:sexvc animated:YES];
        }else if (indexPath.row==3){
            ZCMeBirthdayVC *birthdayvc = [[ZCMeBirthdayVC alloc]init];
            birthdayvc.hidesBottomBarWhenPushed = YES;
            birthdayvc.birthdayStr =[NSString stringWithFormat:@"%@",[self.dataDict objectForKey:@"birthday"]];
            [self.navigationController pushViewController:birthdayvc animated:YES];
        }else{
            ZCAdressVC *adress = [[ZCAdressVC alloc]init];
            adress.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:adress animated:YES];
        }
    }
    [self performSelector:@selector(unselectCell:) withObject:nil afterDelay:0.3];
}

-(void)unselectCell:(id)sender{
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

#pragma mark 点击了头像
-(void)TapGestureRecognizerClick:(UITapGestureRecognizer *)reco{
    NSLog(@"点击了头像");
    
    FSMediaPicker *mediaPicker = [[FSMediaPicker alloc] init];
    mediaPicker.delegate = self;
    
    if (DEVICE_SYSTEM_VERSION) {
        [mediaPicker showFromView:self.view];
    }else{
        [mediaPicker showActionSheet:self.view];
    }
}

- (void)mediaPicker:(FSMediaPicker *)mediaPicker didFinishWithMediaInfo:(NSDictionary *)mediaInfo
{
    NSLog(@"img = %@",mediaInfo.originalImage);
    
    UIImage *picImage = [mediaInfo.originalImage resizedImageWithWidth:55 height:55 opaque:YES scale:0];
    NSMutableArray *imgarray = [[NSMutableArray alloc]initWithObjects:picImage,nil];
    ProgressHUDStr;
    [NetworkManager requestModifyavatarWithMid:UserModel.mid password:UserModel.password avatar:imgarray success:^(NSData *data) {
        ProgressDismiss;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"dic = %@",dic);
            NSString *strerr = [NSString stringWithFormat:@"%@",[dic objectForKey:@"err"]];
        if ([strerr isEqualToString:@"0"]){
            NSLog(@"sdfa");
            self.headIconImage = mediaInfo.circularEditedImage;
            [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationNone];
        }
    } failure:^(NSError *error) {
        ProgressDismiss;
    }];
}

- (void)mediaPickerDidCancel:(FSMediaPicker *)mediaPicker
{
    NSLog(@"%s",__FUNCTION__);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
